// package中name为大写字符 报错
const express = require("express");
const jsonServer = require("json-server");
const Axios = require("axios");
const bcryptjs = require("bcryptjs");
const routes = jsonServer.router("./db.json");
const middlewares = jsonServer.defaults();

Axios.defaults.baseURL = "http://localhost:9090";

const server = express();

// req.body 处理
server.use(express.json());
server.use(express.urlencoded({ extended: true }));

// 跨域处理
server.use((req, res, next) => {
  res.set("Access-Control-Allow-Origin", "*");
  next();
});

// 延迟处理
const timer = (time = 500) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve();
    }, time);
  });
};
server.use(async (req, res, next) => {
  await timer();
  next();
});

// 自己在实现一些接口
//1 注册
server.post("/sign-up", async (req, res) => {
  // 1. 获取前端传递过来的 username 、password 、gender
  // 2. 直接使用 Axios 来调用 json-server 的 users 这个接口来存进去
  const response = await Axios.get("/users", {
    params: { username: req.body.username }
  });

  if (response.data.length > 0) {
    // 用户名已经注册过了
    res.send({
      code: -1,
      msg: "用户名已经被注册过了"
    });

    return;
  }

  const { data } = await Axios.post("/users", {
    ...req.body,
    password: await bcryptjs.hash(req.body.password, 10)
  });
  res.send({
    code: 0,
    msg: "注册成功",
    data
  });
});
// 登录
server.post("/sign-in", async (req, res) => {
  const { username, password } = req.body;
  // axios去改变db.json文件  根据用户名查找
  const { data } = await Axios.get("/users", {
    params: {
      username
    }
  });

  if (data.length <= 0) {
    res.send({
      code: -1,
      msg: "用户名或密码错误"
    });

    return;
  }
  console.log(data);
  /* 
  [ {
    username:
    password:
    gender:
    id:
  }]
  */
  // 有的话
  const user = data[0];
  //比较密码
  const isOk = await bcryptjs.compare(password, user.password);
  if (isOk) {
    res.send({
      code: 0,
      msg: "登录成功",
      data: user
    });
  } else {
    res.send({
      code: -1,
      msg: "用户名或密码错误"
    });
  }
});

// json-server 假数据 操作db.json文件
server.use(middlewares);
server.use(routes);

server.listen(9090);
